package com.jinzhi.jzweb.service.impl;

import com.jinzhi.common.utils.ShiroUtils;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzapi.utils.JWTUtil;
import com.jinzhi.jzweb.service.WxValidationService;
import com.jinzhi.sys.service.UserService;
import groovy.util.logging.Commons;
import lombok.SneakyThrows;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/*
 *  @author : JingChangTian
 *  @date   : 2023/7/19 11:11
 *  @description :
 *
 */
@Service
@Commons
public class WxValidationImpl implements WxValidationService {

    private final StringRedisTemplate redisTemplate;

    private final CloseableHttpClient wxPayClient;

    private final UserService userService;

    public WxValidationImpl(StringRedisTemplate redisTemplate, CloseableHttpClient wxPayClient, UserService userService) {
        this.redisTemplate = redisTemplate;
        this.wxPayClient = wxPayClient;
        this.userService = userService;
    }

    /**
     * appid
     */
    private final String appid = "wx11786f27a7ac6bd5";

    //private final String appid = "wx07f09972179a2df6";

    /**
     * secret
     */
    //private final String appsecret = "2a38964d2aa7e2580172e9300e2a5bac";
    private final String appsecret = "95bb5122f0a848cdbb75709d7b7dab16";

    /**
     * 30分钟刷新一次，定时刷新token
     * @return
     */
    @SneakyThrows
    @Scheduled(fixedDelay=30*60*1000)
    @Override
    public String accessToken() {
        HttpClient httpclient = HttpClients.createDefault();
        Map<String,Object> map = new HashMap<>();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" +appid + "&secret=" + appsecret + "";
        HttpGet httpGet = httpGet(url);
        try {
            HttpResponse response = httpclient.execute(httpGet);
            //获取响应体
            String bodyAsString = EntityUtils.toString(response.getEntity());
            //响应码
            int statusCode = response.getStatusLine().getStatusCode();
            //返回参数
            map = JSONObject.fromObject(bodyAsString);
           /* if(Integer.parseInt(map.get("expires_in").toString())==7200){
                //处理成功,获取获取token缓存到redis
                redisTemplate.delete("access_token");
                redisTemplate.opsForValue().set("access_token",);
                ValueOperations<String, String> stringStringValueOperations = redisTemplate.opsForValue();
                System.out.println(LocalDateTime.now()+":获取token------------"+stringStringValueOperations.get("access_token"));
            }*/
        }catch (Exception e){
            e.printStackTrace();
        }
        return map.get("access_token").toString();
    }

    @SneakyThrows
    @Override
    public Map msgValidation(String content) {
        HttpClient httpclient = HttpClients.createDefault();
        UserDO userDO = userService.selectById(JWTUtil.getUser().getId());
        Map<String,Object> map = new HashMap<>();

        String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token="+accessToken();
        //根据userId查询获取openid
        map.put("openid",userDO.getCerOpenId());
        //场景枚举值（1 资料；2 评论；3 论坛；4 社交日志）
        map.put("scene",2);
        //固定版本号
        map.put("version",2);
        //需检测的文本内容，文本字数的上限为2500字，需使用UTF-8编码
        map.put("content",content);
        String body = JSONObject.fromObject(map).toString();
        //封装请求
        HttpPost httpPost = httpPost(url,body);
        try {
            HttpResponse response = httpclient.execute(httpPost);
            //获取响应体
            String bodyAsString = EntityUtils.toString(response.getEntity());
            //响应码
            int statusCode = response.getStatusLine().getStatusCode();
            //返回参数
            map = JSONObject.fromObject(bodyAsString);
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }





    /**
     * 封装需要请求的链接及头部设置
     *
     * @param url   请求地址
     * @return httpGet
     */
    private HttpGet httpGet(String url) {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Content-Type","application/json");
        httpGet.setHeader("Accept", "application/json");
        return httpGet;
    }


    /**
     * 封装需要请求的链接及头部设置
     *
     * @param url   请求地址
     * @param param 携带的参数
     * @return httpPost
     */
    private HttpPost httpPost(String url, String param) {
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(param, "utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type","application/json");
        httpPost.setHeader("Accept", "application/json");
        return httpPost;
    }
}
